const OSS = require("aliyun-oss");
const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
const ora = require("ora");

const spinner = ora("upload files...");

const log = console.log;

const config = require("../config");

const option = config.aliOSS;

option.bucket =
  process.argv[2] === "prod"
    ? "chanshike-amp"
    : process.argv[2] === "stage"
    ? "csk-amp-stage"
    : "csk-amp-dev";

const oss = OSS.createClient(option);

const OSS_DIR_NAME = "web/";

function readFiles(dir, paths = []) {
  const files = fs.readdirSync(dir);

  files.forEach(filename => {
    const fullPath = path.join(dir, filename);

    const stat = fs.statSync(fullPath);

    if (stat.isDirectory()) {
      readFiles(path.join(dir, filename), paths);
    } else {
      paths.push(fullPath);
    }
  });
}

const paths = [];
readFiles(path.join(__dirname, "..", "dist"), paths);

const promises = [];
paths.forEach(path => {
  const p = new Promise(function(resolve, reject) {
    const o = {
      bucket: option.bucket,
      object: OSS_DIR_NAME + path.split("/dist/")[1],
      source: path
    };

    oss.putObject(o, function(err, res) {
      if (err) {
        reject(path.split("/dist/")[1] + ": " + err);
      } else {
        resolve("upload success: " + res.objectUrl);
      }
    });
  });

  promises.push(p);
});

spinner.start();
Promise.all(promises)
  .then(() => {
    spinner.stop();
    log(chalk.black.bgGreen(" DONE "), "Upload files successfully.");
    log(
      chalk.black.bgBlue(" PREVIEW "),
      chalk.blue(
        `https://${option.bucket}.oss-cn-hangzhou.aliyuncs.com/web/index.html`
      )
    );
  })
  .catch(function(err) {
    spinner.stop();
    log(chalk.red(err));
  });
